package com.hxy.security;


import com.hxy.entity.AuthUser;
import com.hxy.mapper.AuthUserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class AuthUserConfigure implements UserDetailsService {

    @Resource
    AuthUserMapper authUserMapper;

    /**
     * 根据用户名获取用户信息
     *
     * @param s：表单提交得用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("s:" + s);
        // 获取用户详细信息
        AuthUser user = authUserMapper.findByUsername(s);
        System.out.println("user:" + user);

        // 用户存在
        if (null != user) {

            String roles="";
            // 获取用户角色权限
            if(user.getUname().equals("zhangsan")){
                // ROLE_ADMIN是角色
                // select,add,update,delete是权限
                roles="ROLE_ADMIN,select,add,update,delete";
            }
            if(user.getUname().equals("lisi")){
                roles="ROLE_TEST,select";
            }

            List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(roles);

            // 设置用户权限
            user.setAuthorities(authorityList);
        }

        return user;
    }
}
